package com.gf.forcesystem.websocket;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.gf.forcesystem.mq.ForeInfoMqSender;
import com.gf.framework.common.utils.SpringContextUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

/**
 * @author gaofei
 * @date 2022/6/20 21:40
 * 兵力系统客户端，只显示数据
 */
@Api(tags = "兵力系统客户端websocket接口")
@Component
@Slf4j
@ServerEndpoint("/ws/forceclient/{userId}")
public class ForceClientWebSocketServiceImpl {
    private Session session;
    private String userId;

    private ForceClientWebsocketManager forceClientWebsocketManager;

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) throws Exception{
        this.session = session;

        forceClientWebsocketManager = SpringContextUtil.getBean(ForceClientWebsocketManager.class);
        forceClientWebsocketManager.register(userId, this);
        this.userId = userId;
    }

    @OnClose
    public void close() {
        if (StringUtils.isBlank(userId)) {
            return;
        }
        forceClientWebsocketManager.unRegister(userId);
    }

    @OnMessage
    public void onMessage(String message) {
        SpringContextUtil.getBean(ForeInfoMqSender.class).send(message);
    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("用户错误:"+this.userId+",原因:"+error.getMessage());
    }

    /**
     * 实现服务
     * 器主动推送
     */
    public synchronized void sendMessage(String message) {
        try {
            this.session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            log.error("ForceClientWebSocketServiceImpl:", e);
        }
    }
}
